package com.hjm.admin.moule.view.activity.impl;

import android.Manifest;
import android.animation.Animator;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.color.ColorChooserDialog;
import com.allen.library.utils.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.hjm.admin.moule.R;
import com.hjm.admin.moule.db.entity.UserBean;
import com.hjm.admin.moule.db.helpter.UserHelper;
import com.hjm.admin.moule.model.AppUpdateBean;
import com.hjm.admin.moule.model.MainMenuBean;
import com.hjm.admin.moule.utils.AppUpdateUtils;
import com.hjm.admin.moule.utils.BaseUtils;
import com.hjm.admin.moule.utils.Constant;
import com.hjm.admin.moule.utils.SharedPreUtils;
import com.hjm.admin.moule.utils.SnackBarUtils;
import com.hjm.admin.moule.utils.ThemeUtils;
import com.hjm.admin.moule.view.activity.ISetting;
import com.hjm.admin.moule.view.adapter.MainMenuAdapter;
import com.hjm.admin.moule.view.base.BaseActivity;
import com.hjm.admin.moule.view.fragment.BookClassifyFragment;
import com.hjm.admin.moule.view.fragment.impl.BookShelfFragment;
import com.hjm.admin.moule.view.fragment.impl.ScanBookFragment;
import com.hjm.admin.moule.viewmodel.activity.VMSettingInfo;
import com.hjm.admin.moule.widget.ResideLayout;
import com.hjm.admin.moule.widget.theme.ColorRelativeLayout;
import com.hjm.admin.moule.widget.theme.ColorUiUtil;
import com.hjm.admin.moule.widget.theme.Theme;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements ColorChooserDialog.ColorCallback, ISetting {
    @BindView(R.id.iv_avatar)
    ImageView mIvAvatar;
    @BindView(R.id.tv_desc)
    TextView mTvDesc;
    @BindView(R.id.top_menu)
    LinearLayout mTopMenu;
    @BindView(R.id.rv_menu)
    RecyclerView mRvMenu;
    @BindView(R.id.tv_theme)
    TextView mTvTheme;
    @BindView(R.id.tv_setting)
    TextView mTvSetting;
    @BindView(R.id.bottom_menu)
    LinearLayout mBottomMenu;
    @BindView(R.id.menu)
    ColorRelativeLayout mMenu;
    @BindView(R.id.container)
    FrameLayout mContainer;
    @BindView(R.id.resideLayout)
    ResideLayout mResideLayout;
    @BindView(R.id.iv_toolbar_more)
    AppCompatImageView mIvToolBarMore;
    @BindView(R.id.iv_toolbar_back)
    AppCompatImageView mIvToolbarBack;
    @BindView(R.id.tv_toolbar_title)
    TextView mTvToolBarTitle;
    @BindView(R.id.iv_setting)
    AppCompatImageView iv_setting;
    @BindView(R.id.iv_theme)
    AppCompatImageView iv_theme;

    private MainMenuAdapter mainMenuAdapter;
    private FragmentManager fragmentManager;
    private String currentFragmentTag;
    private List<MainMenuBean> menuBeans;
    private long fistTime = 0;
    private VMSettingInfo mModel;
    private String mUserName;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mModel = new VMSettingInfo(this, this);
        setBinddingView(R.layout.activity_main, mModel);
        initThemeToolBar("分类", R.drawable.ic_classify, R.drawable.ic_search,
                v -> mResideLayout.openPane(),
                v -> startActivity(BookSearchActivity.class));
        mModel.appUpdate(false);
        fragmentManager = getSupportFragmentManager();
        initMenu();
        switchFragment("分类");
    }

    private void initMenu() {
        getMenuData();
        mRvMenu.setLayoutManager(new LinearLayoutManager(this));
        mainMenuAdapter = new MainMenuAdapter(menuBeans);
        mRvMenu.setAdapter(mainMenuAdapter);
        mainMenuAdapter.setOnItemClickListener((adapter, view, position) -> {
            String name = menuBeans.get(position).getName();
            switch (name) {
                case "扫描书籍":
                    RxPermissions rxPermissions = new RxPermissions(this);
                    rxPermissions.requestEach(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .subscribe(permission -> {
                                        if (permission.granted) {
                                            MainActivity.this.switchFragment(name);
                                            setToolBar(name, position);
                                        } else if (permission.shouldShowRequestPermissionRationale) {
                                            mResideLayout.closePane();
                                            ToastUtils.showToast("权限拒绝");
                                        } else {
                                            mResideLayout.closePane();
                                            SnackBarUtils.makeShort(MainActivity.this.getWindow().getDecorView(), "读写权限被禁止,移步到应用管理允许权限")
                                                    .show("去设置", v -> BaseUtils.getAppDetailSettingIntent(mContext, getPackageName()));
                                        }

                                    }
                            );
                    break;
                case "书架":
                    switchFragment(name);
                    setToolBar(name, position);
                    break;
                case "分类":
                    switchFragment(name);
                    setToolBar(name, position);
                    break;
                case "缓存列表":
                    startActivity(BookDownloadActivity.class);
                    mResideLayout.closePane();
                    break;
                case "意见反馈":
                    startActivity(FeedBackActivity.class);
                    mResideLayout.closePane();
                    break;
                case "关于作者":
                    startActivity(AboutMineActivity.class);
                    mResideLayout.closePane();
                    break;
            }
        });
    }

    private void setToolBar(String name, int position) {
        mTvToolBarTitle.setText(name);
        mIvToolbarBack.setImageResource(menuBeans.get(position).getIcon());
        mResideLayout.closePane();
    }

    private List<MainMenuBean> getMenuData() {
        menuBeans = new ArrayList<>();
        String[] menuName = getResources().getStringArray(R.array.main_menu_name);
        TypedArray menuIcon = getResources().obtainTypedArray(R.array.main_menu_icon);
        for (int i = 0; i < menuName.length; i++) {
            MainMenuBean menuBean = new MainMenuBean();
            menuBean.setName(menuName[i]);
            menuBean.setIcon(menuIcon.getResourceId(i, 0));
            menuBeans.add(menuBean);
        }
        return menuBeans;
    }

    private void switchFragment(String name) {
        if (currentFragmentTag != null && currentFragmentTag.equals(name))
            return;
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
        Fragment currentFragment = fragmentManager.findFragmentByTag(currentFragmentTag);
        if (currentFragment != null)
            ft.hide(currentFragment);
        Fragment foundFragment = fragmentManager.findFragmentByTag(name);
        if (foundFragment == null) {
            switch (name) {
                case "分类":
                    foundFragment = BookClassifyFragment.newInstance();
                    break;
                case "书架":
                    foundFragment = BookShelfFragment.newInstance();
                    break;
                case "扫描书籍":
                    foundFragment = ScanBookFragment.newInstance();
                    break;
            }
        }
        if (foundFragment.isAdded()) {
            ft.show(foundFragment);
        } else {
            ft.add(R.id.container, foundFragment, name);
        }
        ft.commit();
        currentFragmentTag = name;
    }

    @OnClick({R.id.iv_avatar, R.id.iv_theme, R.id.tv_theme, R.id.iv_setting, R.id.tv_setting})
    public void onViewClicked(View v) {
        String username = SharedPreUtils.getInstance().getString("username", "");
        switch (v.getId()) {
            case R.id.iv_avatar:
                if (username.equals(""))
                    startActivity(LoginActivity.class);
                else
                    startActivity(UserInfoActivity.class);
                break;
            case R.id.iv_theme:
            case R.id.tv_theme:
                new ColorChooserDialog.Builder(this, R.string.app_name)
                        .customColors(R.array.colors, null)
                        .doneButton(R.string.done)
                        .cancelButton(R.string.cancel)
                        .allowUserColorInput(false)
                        .allowUserColorInputAlpha(false)
                        .show(this);
                break;
            case R.id.iv_setting:
            case R.id.tv_setting:
                if (username.equals(""))
                    startActivity(LoginActivity.class);
                else
                    startActivity(SettingActivity.class);
                break;
        }

    }

    @Override
    public void appUpdate(AppUpdateBean appUpdateBean) {
//        AppUpdateUtils.getInstance().appUpdate(this, appUpdateBean);
        downApk();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void stopLoading() {

    }

    @Override
    public void onColorSelection(@NonNull ColorChooserDialog dialog, int selectedColor) {
        if (selectedColor == ThemeUtils.getThemeColor2Array(this, R.attr.colorPrimary))
            return;
        if (selectedColor == getResources().getColor(R.color.colorBluePrimary)) {
            setTheme(R.style.BlueTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Blue);
        } else if (selectedColor == getResources().getColor(R.color.colorRedPrimary)) {
            setTheme(R.style.RedTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Red);

        } else if (selectedColor == getResources().getColor(R.color.colorBrownPrimary)) {
            setTheme(R.style.BrownTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Brown);

        } else if (selectedColor == getResources().getColor(R.color.colorGreenPrimary)) {
            setTheme(R.style.GreenTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Green);

        } else if (selectedColor == getResources().getColor(R.color.colorPurplePrimary)) {
            setTheme(R.style.PurpleTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Purple);

        } else if (selectedColor == getResources().getColor(R.color.colorTealPrimary)) {
            setTheme(R.style.TealTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Teal);

        } else if (selectedColor == getResources().getColor(R.color.colorPinkPrimary)) {
            setTheme(R.style.PinkTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Pink);

        } else if (selectedColor == getResources().getColor(R.color.colorDeepPurplePrimary)) {
            setTheme(R.style.DeepPurpleTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.DeepPurple);

        } else if (selectedColor == getResources().getColor(R.color.colorOrangePrimary)) {
            setTheme(R.style.OrangeTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Orange);

        } else if (selectedColor == getResources().getColor(R.color.colorIndigoPrimary)) {
            setTheme(R.style.IndigoTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Indigo);

        } else if (selectedColor == getResources().getColor(R.color.colorLightGreenPrimary)) {
            setTheme(R.style.LightGreenTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.LightGreen);

        } else if (selectedColor == getResources().getColor(R.color.colorDeepOrangePrimary)) {
            setTheme(R.style.DeepOrangeTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.DeepOrange);

        } else if (selectedColor == getResources().getColor(R.color.colorLimePrimary)) {
            setTheme(R.style.LimeTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Lime);

        } else if (selectedColor == getResources().getColor(R.color.colorBlueGreyPrimary)) {
            setTheme(R.style.BlueGreyTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.BlueGrey);

        } else if (selectedColor == getResources().getColor(R.color.colorCyanPrimary)) {
            setTheme(R.style.CyanTheme);
            SharedPreUtils.getInstance().setCurrentTheme(Theme.Cyan);
        }
        final View rootView = getWindow().getDecorView();
        rootView.setDrawingCacheEnabled(true);
        rootView.buildDrawingCache(true);
        final Bitmap localBitmap = Bitmap.createBitmap(rootView.getDrawingCache());
        if (null != localBitmap && rootView instanceof ViewGroup) {
            final View tmpView = new View(getApplicationContext());
            tmpView.setBackgroundDrawable(new BitmapDrawable(getResources(), localBitmap));
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            ((ViewGroup) rootView).addView(tmpView, params);
            tmpView.animate().alpha(0).setDuration(400).setListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    ColorUiUtil.changeTheme(rootView, getTheme());
                    System.gc();
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    ((ViewGroup) rootView).removeView(tmpView);
                    localBitmap.recycle();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
        }
    }


    @Override
    public void onColorChooserDismissed(@NonNull ColorChooserDialog dialog) {

    }

    public void setLeftSlide(boolean b) {
        mResideLayout.setCanLeftSlide(b);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mUserName = SharedPreUtils.getInstance().getString("username", "");
        try {
            if (!mUserName.equals("")) {
                UserBean userBean = UserHelper.getsInstance().findUserByName(mUserName);
                Glide.with(mContext).load(Constant.BASE_URL + userBean.getIcon())
                        .apply(new RequestOptions().transform(new CircleCrop()).diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true))
                        .into(mIvAvatar);
                mTvDesc.setText(userBean.getBrief());
                mTvSetting.setText("设置");
            } else {
                Glide.with(mContext).load(R.mipmap.ic_launcher).apply(new RequestOptions().transform(new CircleCrop()).diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true)).into(mIvAvatar);
                mTvDesc.setText("未登录");
                mTvSetting.setText("登录");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        if (mResideLayout.isOpen()) {
            mResideLayout.closePane();
        } else {
            long secondTime = System.currentTimeMillis();
            if (secondTime - fistTime < 2000) {
                finish();
            } else {
                SnackBarUtils.makeShort(mTvToolBarTitle, "再按一次退出").show();
                fistTime = System.currentTimeMillis();
            }
        }
    }

    public void downApk() {
        String url = "https://www.hongjimeng.net/UploadFiles/APP/HJMEmployeesV2.3.1.apk";
        AppUpdateBean appUpdateBean = new AppUpdateBean();
        appUpdateBean.setDownloadurl(url);
        AppUpdateUtils.getInstance().appUpdate(this, appUpdateBean);
    }
}
